﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using AtDevice;
using Mokkula.Properties;

namespace Mokkula
{
    public partial class TextMessageControl : UserControl
    {
        private string _currentFilter = "";
        private MessageStatus _currentStatus = MessageStatus.All;
        private ISMSInterface _smsInterface;
        private ImageList _imageList = new ImageList();

        public TextMessageControl()
        {
            InitializeComponent();
            folderView.Nodes[0].Expand();
            this.Dock = DockStyle.Fill;
            DeviceHandler.DeviceOpened += delegate {
                _smsInterface = DeviceHandler.Get().GetSMSInteface();
                newMessageButton.Enabled = true;
                RefreshMessages();
            };
            InitImageList();
        }

        private void InitImageList()
        {
            _imageList.Images.Add(Resources.message_16x16);
            _imageList.Images.Add(Resources.message_new_16x16);
            messageList.SmallImageList = _imageList;
        }

        private void RefreshMessages()
        {
            messageList.Items.Clear();
            List<SMS> messages = _smsInterface.ListMessages(_currentStatus);
            foreach (SMS sms in messages)
            {
                AppendItem(sms);
            }
        }

        private void AppendItem(SMS sms)
        {
            ListViewItem item = new ListViewItem(new string[] { sms.Number, sms.Content, sms.TimeStamp, sms.Status.ToString() });
            item.ImageIndex = sms.Status == MessageStatus.ReceivedUnread ? 1 : 0;
            item.Tag = sms;
            if (ItemMatches(item, _currentFilter))
                messageList.Items.Add(item);
        }

        private void searchTextBox_TextChanged(object sender, EventArgs e)
        {
            _currentFilter = searchTextBox.Text;

            if (_smsInterface != null)
                RefreshMessages();
        }

        private static bool ItemMatches(ListViewItem item, string filter)
        {
            foreach (ListViewItem.ListViewSubItem subItem in item.SubItems)
            {
                if (subItem.Text.ToLower().Contains(filter.ToLower()))
                    return true;
            }
            return false;
        }

        private void newMessageButton_Click(object sender, EventArgs e)
        {
            new TextMessageNewForm("", "").Show();
        }

        private void sendButton_Click(object sender, EventArgs e)
        {
            SMS sms = GetSelectedMessage();
            new TextMessageNewForm("", sms.Content).Show();
        }

        private void replyButton_Click(object sender, EventArgs e)
        {
            SMS sms = GetSelectedMessage();
            new TextMessageNewForm(sms.Number, "").Show();
        }

        private SMS GetSelectedMessage()
        {
            ListViewItem selectedItem = this.messageList.SelectedItems[0];
            SMS message = (SMS)selectedItem.Tag;

            return message;
        }

        private void messageList_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
        {
            if (messageList.SelectedItems.Count > 0)
                EnableButtons();
            else
                DisableButtons();
        }

        private void EnableButtons()
        {
            deleteButton.Enabled = true;
            replyButton.Enabled = true;
            sendButton.Enabled = true;
        }

        private void DisableButtons()
        {
            deleteButton.Enabled = false;
            replyButton.Enabled = false;
            sendButton.Enabled = false;
        }

        private void folderView_AfterSelect(object sender, TreeViewEventArgs e)
        {
            switch(e.Node.Name)
            {
                case "InboxNode":
                    _currentStatus = MessageStatus.Received;
                    break;
                case "OutboxNode":
                    _currentStatus = MessageStatus.StoredSent;
                    break;
                case "DraftNode":
                    _currentStatus = MessageStatus.StoredUnsent;
                    break;
                case "DeletedNode":
                    _currentStatus = MessageStatus.StoredUnsent;
                    break;
                case "ReportsNode":
                    _currentStatus = MessageStatus.StoredUnsent;
                    break;
            }
            RefreshMessages();
        }

        private void messageList_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (messageList.SelectedItems.Count == 1)
            {
                DisplayInPane(GetSelectedMessage());
            }
        }

        private void AppendLineToPane(string label, string content)
        {
            this.messageView.SelectionFont = new Font(Control.DefaultFont, FontStyle.Bold);
            this.messageView.AppendText(label + " ");
            this.messageView.SelectionFont = new Font(Control.DefaultFont, FontStyle.Regular);
            this.messageView.AppendText(content + "\n");
        }

        private void DisplayInPane(SMS sms)
        {
            this.messageView.Text = "";
            AppendLineToPane("Number:", sms.Number);
            AppendLineToPane("Time:", sms.TimeStamp);
            AppendLineToPane("Status:", sms.Status.ToString());
            AppendLineToPane("Content:", sms.Content);
        }

        private void deleteButton_Click(object sender, EventArgs e)
        {
            DeleteSelectedMessages();
        }

        private void TextMessageControl_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
                DeleteSelectedMessages();
        }

        private void DeleteSelectedMessages()
        {
            List<int> ids = new List<int>();
            foreach (ListViewItem item in messageList.SelectedItems)
            {
                ids.Add(((SMS)item.Tag).Identifier);
                messageList.Items.Remove(item);
            }

            foreach (int id in ids)
            {
                _smsInterface.DeleteSMS(id);
            }
        }
    }
}
